#!/usr/bin/python
# -*- coding: utf-8 -*-

##
 # Copyright 2009 Caio Souza
 # This file is part of Rpyg.
 #
 # Rpyg is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # Rpyg is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with Rpyg. If not, see <http://www.gnu.org/licenses/>.
 ##

'''Módulo com a classe principal do jogo.'''

from threading import Thread, enumerate, current_thread

import pygame

from rpyg.Joystick import *

class Game(Thread):
    '''Classe principal da engine, agrupa todos os outros objetos.'''

    def __init__(self, dungeons):
        '''Cria um jogo a partir da lista de dungeons.'''

        Thread.__init__(self)
        pygame.init()
        self._dungeons = dungeons
        self._dungeon = dungeons[0]
        self._clock = pygame.time.Clock()
        self.running = True
        self.setDaemon(True)

        pygame.event.set_allowed(None)
        pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN, pygame.KEYUP])

    def start(self):
        '''Inicia a thread do jogo e a checagem de eventos.'''

        Thread.start(self)

        rk = Joystick.registered_keys
        while self.running:
            event = pygame.event.wait()
            if event.type == pygame.QUIT: self.exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE: self.exit()

                joystick = rk.get(event.key)
                if joystick is not None:
                    for j in joystick:
                        j.pressed(event.key)

            elif event.type == pygame.KEYUP:
                joystick = rk.get(event.key)
                if joystick is not None:
                    for j in joystick:
                        j.released(event.key)

    def run(self):
        '''Método da thread do jogo.'''

        while self.running:
            self._dungeon.update()
            self._clock.tick(60)

    def exit (self):
        '''Termina todas as threads do jogo.'''

        self.running = False
        threads_size = 0
        ct = current_thread()
        for thread in enumerate():
            if thread is not ct and not thread.isDaemon(): thread.exit()
            else: threads_size += 1;
        while len(enumerate()) > threads_size: pygame.time.wait(1)
